package com.demo.boot.commmon.config;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.demo.boot.bean.Permission;
import com.demo.boot.bean.Role;
import com.demo.boot.bean.User;
import com.demo.boot.service.UserService;

public class ShiroRealm extends AuthorizingRealm{
	
	private static final Logger logger = LoggerFactory.getLogger(ShiroRealm.class);
	
	@Autowired
	private UserService userService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		logger.info("##################执行Shiro权限认证##################");
		User user = (User)super.getAvailablePrincipal(principals);
		User loginUser = userService.getUserByName(user.getName());
		if(loginUser!=null){
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			List<Role> roles = loginUser.getRoles();
			Set<String> roleNames = new HashSet<String>();
			for (Role role : roles) {
				roleNames.add(role.getName());
				List<Permission> permissions = role.getPermissions();
				for (Permission permission : permissions) {
					info.addStringPermission(permission.getCode());
				}
			}
			info.setRoles(roleNames);
			return info;
		}
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
		logger.info("验证当前Subject时获取到token为：" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE)); 
		
		User user = userService.getUserByName(token.getUsername());
		if(user!=null){
			return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
		}
		
		return null;
	}

}
